package cn.edu.hbpu.handler;

import cn.edu.hbpu.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author lcy
 * @date 2022/8/5 18:32
 * @description
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理全局异常、运行时异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler({Exception.class, RuntimeException.class})
    public R<Object> globalException(Exception e) {
        String message = e.getMessage();
        log.info("exception message = {}", message);
        if (message.contains("Duplicate entry") && message.contains("user.UNIQUE_USER_NAME")) {
            return new R<>(0, "用户名重复");
        }
        return new R<>(0, "服务器错误，请稍后重试");
    }

    /**
     * 处理自定义异常、认证异常、权限异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler({CustomException.class, AuthenticationException.class, AccessDeniedException.class, BadCredentialsException.class})
    public R<Object> customedException(Exception e) {
        log.info("exception message = {}", e.getMessage());
        return new R<>(0, e.getMessage());
    }
}
